/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddTableDialog.java
 *
 * Created on May 26, 2012, 12:36:46 PM
 */
package gui;

import dao.ExecTableXML;
import java.awt.Component;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.*;
import pojo.Property;
import pojo.Table;

/**
 *
 * @author HoangLiem
 */
public class AddTableDialog extends javax.swing.JDialog {

    /** Creates new form AddTableDialog */
    private String databaseName;
    private String tableName;
    private int editType;// loai chinh sửa, hay thêm,nếu 1 thì là dialog dùng cho thêm bảng, nếu 2 thì dùng cho update

    public String getDatabaseName() {
        return databaseName;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public int getEditType() {
        return editType;
    }

    public void setEditType(int editType) {
        this.editType = editType;
    }

    public AddTableDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public AddTableDialog(java.awt.Frame parent, boolean modal, int editType) {
        super(parent, modal);
        initComponents();
        this.editType = editType;
    }
// jtbTableInfo.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //  jtbTableInfo.setFillsViewportHeight(true);
    // JScrollPane scrollPane = new JScrollPane(table);

    void initTable() {
        if (this.getEditType() == 1) {
            AddTableModel tempModel = new AddTableModel();
            ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
            data.add(tempModel.initNewRow());
            data.add(tempModel.initNewRow());
            AddTableModel model = new AddTableModel(data);
            jtbTableInfo.setModel(model);
            initColumnSizes(jtbTableInfo);
            TableCellEditor editor = setCombobox();
            jtbTableInfo.getColumnModel().getColumn(1).setCellEditor(editor);
        } else {//truong hop nay là chinh sua bảng, nên lay du lieu tu file roi show len
            Table table = ExecTableXML.getTableFromDatabase(databaseName, tableName);
            if (table != null) {
                ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
                ArrayList<Property> ids = table.getIdList();
                ArrayList<Property> properties = table.getPropertyList();
                if (ids != null && !ids.isEmpty()) {
                    for (int i = 0; i < ids.size(); i++) {
                        Property id = ids.get(i);
                        ArrayList<Object> obj = new ArrayList<Object>();
                        obj.add(id.getName());
                        obj.add(id.getType());
                        obj.add(id.getLength());
                        obj.add(true);
                        obj.add(id.isNotnull());
                        obj.add(id.isUnique());
                        data.add(obj);
                    }
                }
                if (properties != null && !properties.isEmpty()) {
                    for (int i = 0; i < properties.size(); i++) {
                        Property pro = properties.get(i);
                        ArrayList<Object> obj = new ArrayList<Object>();
                        obj.add(pro.getName());
                        obj.add(pro.getType());
                        obj.add(pro.getLength());
                        obj.add(false);
                        obj.add(pro.isNotnull());
                        obj.add(pro.isUnique());
                        data.add(obj);
                    }
                }
                AddTableModel tempModel = new AddTableModel();
                data.add(tempModel.initNewRow());
                data.add(tempModel.initNewRow());
                AddTableModel model = new AddTableModel(data);
                jtbTableInfo.setModel(model);
                initColumnSizes(jtbTableInfo);
                TableCellEditor editor = setCombobox();
                jtbTableInfo.getColumnModel().getColumn(1).setCellEditor(editor);
            } else {
                JOptionPane.showMessageDialog(this, "Table null");
            }
        }
    }

    private void initColumnSizes(JTable table) {
        AddTableModel model = (AddTableModel) table.getModel();
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        ArrayList<Object> longValues = model.getLongValues();
        TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < model.getColumnCount(); i++) {
            column = table.getColumnModel().getColumn(i);
            comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
            comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues.get(i), false, false, 0, i);
            headerWidth = comp.getPreferredSize().width;
            cellWidth = comp.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
        table.setRowHeight(20);
    }

    public TableCellEditor setCombobox() {
        TableCellEditor tce;
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("string");
        comboBox.addItem("integer");
        comboBox.addItem("float");
        comboBox.addItem("double");
        tce = new DefaultCellEditor(comboBox);
        return tce;
    }

    /*
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("string");
    comboBox.addItem("integer");
    comboBox.addItem("float");
    comboBox.addItem("double");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    
    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    }*/
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnTableInfo = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbTableInfo = new javax.swing.JTable();
        jbtAddTable = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add new table");
        setMinimumSize(new java.awt.Dimension(600, 400));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jpnTableInfo.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jtbTableInfo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbTableInfo);

        javax.swing.GroupLayout jpnTableInfoLayout = new javax.swing.GroupLayout(jpnTableInfo);
        jpnTableInfo.setLayout(jpnTableInfoLayout);
        jpnTableInfoLayout.setHorizontalGroup(
            jpnTableInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
        );
        jpnTableInfoLayout.setVerticalGroup(
            jpnTableInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
        );

        jbtAddTable.setText("Alter");
        jbtAddTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAddTableActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpnTableInfo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jbtAddTable, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jpnTableInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtAddTable, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        initTable();
    }//GEN-LAST:event_formWindowOpened

    private void jbtAddTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAddTableActionPerformed
        // TODO add your handling code here:
        String tableName = JOptionPane.showInputDialog("Please enter table name:");
        tableName = tableName.trim();
        if (!tableName.equals("")) {
            if (!ExecTableXML.isExistedTable(databaseName, tableName)) {
                AddTableModel model = (AddTableModel) jtbTableInfo.getModel();
                if (model.isDuplicatedFieldName()) {
                    JOptionPane.showMessageDialog(this, "Duplicated field name");
                    return;
                }
                if (model.getAllFieldName().size() == 0) {
                    JOptionPane.showMessageDialog(this, "No field name");
                    return;
                }
                ArrayList<ArrayList<Object>> data = model.getData();
                Table table = new Table();
                table.setName(tableName);
                ArrayList<Property> ids = new ArrayList<Property>();
                ArrayList<Property> properties = new ArrayList<Property>();
                for (int i = 0; i < data.size(); i++) {
                    ArrayList<Object> rowTable = data.get(i);
                    String name = ((String) rowTable.get(0)).trim();
                    boolean isPrimaryKey = (Boolean) rowTable.get(3);
                    if (!name.equals("")) {
                        Property property = new Property();
                        property.setName((String) rowTable.get(0));
                        property.setType((String) rowTable.get(1));
                        property.setLength((Integer) rowTable.get(2));
                        property.setNotnull((Boolean) rowTable.get(4));
                        property.setUnique((Boolean) rowTable.get(5));
                        if (isPrimaryKey) {
                            ids.add(property);
                        } else {
                            properties.add(property);
                        }
                    }
                }
                table.setIdList(ids);
                table.setPropertyList(properties);
                boolean successAdd = ExecTableXML.addTableToDatabase(databaseName, table);
                if (successAdd) {
                    JOptionPane.showMessageDialog(this, "Add table successfully");
                } else {
                    JOptionPane.showMessageDialog(this, "Add table failed");
                }
            } else {
                JOptionPane.showMessageDialog(this, "Table name was existed");
            }
        } else {
            JOptionPane.showMessageDialog(this, "Table name must be never empty");
        }
    }//GEN-LAST:event_jbtAddTableActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddTableDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddTableDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddTableDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddTableDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AddTableDialog dialog = new AddTableDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtAddTable;
    private javax.swing.JPanel jpnTableInfo;
    private javax.swing.JTable jtbTableInfo;
    // End of variables declaration//GEN-END:variables
}
